package com.lxyk.controller;

import com.lxyk.service.HistoryService;
import com.lxyk.service.WorkerService;
import com.lxyk.vo.MainMenu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/main")
@Slf4j
public class MainMenuController {
    @Autowired
    private WorkerService workerService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RedisTemplate redisTemplate;
    @RequestMapping("/mainMenu")
    public List<MainMenu> MainMenu(){
        //去redis中取mainMenu的所有数据
        List<MainMenu> mainMenu = redisTemplate.opsForList().range("mainMenu", 0, -1);
        //判断是否为空
        if (null == mainMenu || mainMenu.size() == 0){
            log.info("redis没有数据，查询数据库");
            List<MainMenu> list = new ArrayList<>();
            Map<Integer, Integer> map = new HashMap<>();

            historyService.list().forEach(his -> {
                map.put(his.getWorkerId(),map.getOrDefault(his.getWorkerId(),0)+ his.getSendWaterCount());
            });
            workerService.listWorker().forEach(worker -> {
                MainMenu main = new MainMenu();
                //把送水工放到了MainMenu的名称里
                main.setWorkerName(worker.getWorkerName());
                Integer count = map.get(worker.getWid());
                main.setSendWaterCount(count == null ? 0 : count);
                list.add(main);
            });

            if (list.size()<12) {
                //把list 集合 放mainMenu中
                mainMenu.addAll(list);
            }
            for (int i = 0; i < 12; i++) {
                mainMenu.add(list.get(i));

            }
            //排序
            Collections.sort(mainMenu,((o1, o2) -> {
                if (o1.getSendWaterCount() > o1.getSendWaterCount()){
                    return 1;
                }else if (o1.getSendWaterCount() < o2.getSendWaterCount()){
                    return -1;
                }else {
                    return 0;
                }
            }));
            redisTemplate.opsForList().leftPushAll("mainMenu",mainMenu);
        }else {
            log.info("Redis执行了......");
        }
        return mainMenu;
    }
}
